//
//  XGThemeManager.swift
//  TodayNews
//
//  Created by monkey on 2020/2/7.
//  Copyright © 2020 itcast. All rights reserved.
//

import SwiftTheme

/// 主题偏好设置键
fileprivate let kIsNightThemeKey: String = "kIsNightThemeKey"
/// 白天主题配置文件
fileprivate let kDayThemePlistName: String = "TodayNews_DayTheme"
/// 暗黑主题配置文件
fileprivate let kNightThemePlistName: String = "TodayNews_NightTheme"

/// 切换主题通知
let TodayNews_SwitchTheme_Notification: Notification.Name = Notification.Name(rawValue: "TodayNews_SwitchTheme_Notification")

class TodayNewsThemeManager
{
    enum ThemeStyle
    {
        /// 白天
        case day
        /// 暗黑
        case night
    }
    
    /// 单例
    static let shared = TodayNewsThemeManager()
    /// 当前主题
    private(set) var currentTheme: TodayNewsThemeManager.ThemeStyle
    /// 上一主题
    private(set) var beforeTheme: TodayNewsThemeManager.ThemeStyle
    
    /// 切换主题
    /// - Parameter theme: 主题
    func switchTheme(_ theme: TodayNewsThemeManager.ThemeStyle)
    {
        switch theme {
        case .day:
            ThemeManager.setTheme(plistName: kDayThemePlistName, path: .mainBundle)
        case .night:
            ThemeManager.setTheme(plistName: kNightThemePlistName, path: .mainBundle)
        }
        
        beforeTheme = currentTheme
        currentTheme = theme
        UserDefaults.standard.set(theme == .night, forKey: kIsNightThemeKey)
        UserDefaults.standard.synchronize()
        
        NotificationCenter.default.post(name: TodayNews_SwitchTheme_Notification, object: nil, userInfo: nil)
    }
    
    private init()
    {
        let isNightTheme = UserDefaults.standard.bool(forKey: kIsNightThemeKey)
        currentTheme = isNightTheme ? ThemeStyle.night : ThemeStyle.day
        beforeTheme = isNightTheme ? ThemeStyle.day : ThemeStyle.night
        
        let themePlist = isNightTheme ? kNightThemePlistName : kDayThemePlistName
        ThemeManager.setTheme(plistName: themePlist, path: .mainBundle)
        
        ThemeManager.animationDuration = 0
    }
}
